package com.huilian.iotbox.admin.wap.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huilian.iotbox.admin.wap.dao.DisplayRackItemDao;
import com.huilian.iotbox.admin.wap.producer.RabbitProducer;
import com.huilian.iotbox.admin.wap.service.*;
import com.huilian.iotbox.aliyun.service.PubService;
import com.huilian.iotbox.data.cmd.HuiLianDuiBiJiPositiveDataFrameCMD;
import com.huilian.iotbox.data.cmd.PositiveDataFrameCMD;
import com.huilian.iotbox.data.cmd.VendmachPositiveDataFrameCMD;
import com.huilian.iotbox.data.common.RedisKey;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dto.*;
import com.huilian.iotbox.data.enums.*;
import com.huilian.iotbox.data.po.*;
import com.huilian.iotbox.data.properties.ImageProperties;
import com.huilian.iotbox.data.service.BlueToothPubService;
import com.huilian.iotbox.data.utils.SnowflakeIdWorker;
import com.huilian.iotbox.data.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DisplayRackItemServiceImpl implements DisplayRackItemService {

    @Value("${huilian.iot.productKey}")
    private String productKey;
    @Autowired
    private PubService pubService;
    @Resource
    private DisplayRackItemDao displayRackItemDao;
    @Autowired
    private DeviceService deviceService;

    @Resource
    private ProductService productService;

    @Resource
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    @Resource
    private CommodityService commodityService;

    @Resource
    private CommodityStoreUpDownService commodityStoreUpDownService;

    @Resource
    private RabbitProducer rabbitProducer;

    @Autowired
    private DisplayRackService displayRackService;

    @Resource
    private CommodityStockRecordService commodityStockRecordService;

    @Resource
    private CommodityStockRecordItemService commodityStockRecordItemService;

    @Resource
    private ImageProperties imageProperties;

    @Autowired
    private BlueToothPubService blueToothPubService;

    @Override
    public List<DisplayRackItemVo> findDisplayRackItemByDeviceId(DisplayRackItemDto displayRackItemDto) {
        return displayRackItemDao.findDisplayRackItemByDeviceId(displayRackItemDto);
    }

    @Override
    public void insert(DisplayRackItem displayRackItem) {
        displayRackItemDao.insert(displayRackItem);
    }

    @Override
    public void update(DisplayRackItem displayRackItem) {
        displayRackItemDao.update(displayRackItem);
    }

    @Override
    public ServerResponse findAllBoundDisplayRackItemByDeviceId(DisplayRackItemDto displayRackItemDto) {

        if (StringUtils.isEmpty(displayRackItemDto.getDeviceId())) {
            return ServerResponse.createByErrorMessage("缺少参数:设备ID");
        }

        DeviceDto deviceDto = new DeviceDto();
        deviceDto.setId(displayRackItemDto.getDeviceId());
        deviceDto.setUserInfo(displayRackItemDto.getUserInfo());
        final DeviceVo deviceVo = deviceService.findOneDeviceByIdAndPermission(deviceDto);
        if (StringUtils.isEmpty(deviceVo)) {
            return ServerResponse.createByErrorMessage("设备不存在");
        }

        DisplayRackItemDto driDto = new DisplayRackItemDto();
        driDto.setDeviceId(deviceVo.getId());
        driDto.setCommodityId(deviceDto.getCommodityId());
        driDto.setFreightLane(deviceDto.getFreightLane());
        driDto.setIsDelete(false);
        DisplayRackVo displayRackAndItemList = displayRackItemDao.findDisplayRackAndItemList(driDto);

        if (!StringUtils.isEmpty(displayRackAndItemList)) {
            for (DisplayRackItemVo displayRackItemVo : displayRackAndItemList.getDisplayRackItemVoList()) {
                StringBuilder stringBuilder = new StringBuilder("仓位 ");
                if (!StringUtils.isEmpty(displayRackItemVo.getHierarchy()) && !StringUtils.isEmpty(displayRackItemVo.getFreightLane())) {
                    stringBuilder.append(displayRackItemVo.getHierarchy());
//                    stringBuilder.append("-");
//                    stringBuilder.append(displayRackItemVo.getFreightLane());
                } else if (!StringUtils.isEmpty(displayRackItemVo.getHierarchy())) {
                    stringBuilder.append(displayRackItemVo.getHierarchy());
                } else if (!StringUtils.isEmpty(displayRackItemVo.getFreightLane())) {
                    stringBuilder.append(displayRackItemVo.getFreightLane());
                }
                displayRackItemVo.setLocationName(stringBuilder.toString());
                displayRackItemVo.setDisplayRackItemId(displayRackItemVo.getId());
                if (DeviceTypeEnum.ONE_TO_MANY_BOXES.getCode().equals(deviceVo.getDeviceTypeId())) {

                } else if (DeviceTypeEnum.GASHAPON_MACHINE.getCode().equals(deviceVo.getDeviceTypeId())) {
                    if (StringUtils.isEmpty(displayRackItemVo.getRateEach())) {
                        // 可能存在部分扭蛋机类型没有投币单价，没有就默认取设备的投币单价
                        displayRackItemVo.setRateEach(deviceVo.getRateEach());
                    }
                } else {
                    displayRackItemVo.setRateEach(deviceVo.getRateEach());
                }
            }
            log.info(JSON.toJSONString(displayRackAndItemList));
        }

        if (!StringUtils.isEmpty(deviceVo.getPulseSwitchState()) && !deviceVo.getPulseSwitchState()) {
            // 延迟去查它的参数
            Map<String, String> delayMap = new HashMap<>();
            delayMap.put("code", CompositeDelayQueueEnum.INITIATIVE_SEND_QUERY_BASE_PARAMS.getCode());
            delayMap.put("deviceNo", deviceVo.getDeviceNo());
            rabbitProducer.sendReplayLazyQueue(delayMap, 1000);
        }

        return ServerResponse.createBySuccess(displayRackAndItemList);
    }

    @Override
    public ServerResponse findAllGoodsStockAwardByDeviceId(DisplayRackItemDto displayRackItemDto) {
        if (StringUtils.isEmpty(displayRackItemDto.getDeviceId())) {
            return ServerResponse.createByErrorMessage("缺少设备信息");
        }

        DisplayRackItemDto displayRackItemCondition = new DisplayRackItemDto();
        displayRackItemCondition.setDeviceId(displayRackItemDto.getDeviceId());
        displayRackItemCondition.setIsDelete(false);
        List<DisplayRackItemVo> displayRackItemVoList = displayRackItemDao.findDisplayRackItemByDeviceId(displayRackItemCondition);

        if (CollectionUtils.isEmpty(displayRackItemVoList) || displayRackItemVoList.size() == 0) {
            return ServerResponse.createBySuccess(new ArrayList<>());
        }

        // 找到出奖号码
        Map<Integer, Integer> map = new HashMap<>();
        for (DisplayRackItemVo displayRackItemVo : displayRackItemVoList) {
            List<Integer> list = JSON.parseArray(displayRackItemVo.getAward(), Integer.class);
            if (CollectionUtils.isEmpty(list)) {
                continue;
            }
            for (Integer i : list) {
                map.put(i, displayRackItemVo.getFreightLane());
            }
        }

        final Integer totalAward = 91;
        // 从1到91拼装，0是未出奖，1-8对应蛋赏、A-F赏和最终赏
        List<NiuDanAwardVo> awardList = new ArrayList<>();
        NiuDanAwardVo niuDanAwardVo = null;
        for (int i = 1; i <= totalAward; i++) {
            niuDanAwardVo = new NiuDanAwardVo();
            Integer positionId = map.get(i);

            niuDanAwardVo.setId(i);
            if (StringUtils.isEmpty(positionId)) {
                niuDanAwardVo.setPositionId(0);
            } else {
                niuDanAwardVo.setPositionId(positionId);
            }
            awardList.add(niuDanAwardVo);
        }

        return ServerResponse.createBySuccess(awardList);
    }

    @Override
    public List<DisplayRackItemVo> findDisplayRackItemByDisplayRackId(Long displayRackId) {
        return displayRackItemDao.findDisplayRackItemByDisplayRackId(displayRackId);
    }

    /**
     * 根据deviceId查询层级
     */
    @Override
    public List<DisplayRackItemVo> findVendingMachine(DisplayRackItemDto displayRackItemDto) {
        displayRackItemDto.setIsDelete(false);
        displayRackItemDto.setEnabled(true);
        return displayRackItemDao.findAisleByDeviceId(displayRackItemDto);
    }


    /**
     * 查询售货机 缺货量、货道总数、库存总数、现库存量
     */
    @Override
    public DisplayRackItemVo findInventoryByDisplayRackId(Long displayRackId) throws Exception {
        if (ObjectUtils.isEmpty(displayRackId)) {
            throw new Exception("缺少参数:displayRackId父展架ID");
        }
        DisplayRackItemVo displayRackItemVo = new DisplayRackItemVo();
        Integer freightLaneCount = 0;
        Integer capacityCount = 0;
        Integer stockCount = 0;
        List<DisplayRackItemVo> displayRackItemVoList = this.findDisplayRackItemByDisplayRackId(displayRackId);
        for (DisplayRackItemVo dri : displayRackItemVoList) {
            if (!ObjectUtils.isEmpty(dri.getCommodityId())) {
                freightLaneCount++;
                capacityCount += dri.getCapacity();
                stockCount += dri.getStock();
            }
        }
        displayRackItemVo.setFreightLaneCount(freightLaneCount);
        displayRackItemVo.setCapacityCount(capacityCount);
        displayRackItemVo.setStockCount(stockCount);
        displayRackItemVo.setScarceStock(capacityCount - stockCount);
        return displayRackItemVo;
    }

    /**
     * 查询货道并清空 stock库存数
     */
    @Override
    public void oneClickClearance(DisplayRackItemDto displayRackItemDto) {
        displayRackItemDto.setNotBound(true);
        List<DisplayRackItemVo> displayRackItemVoList = displayRackItemDao.findAllByDeviceId(displayRackItemDto);
        List<RestockNotificationVo> restockNotificationVoList = new ArrayList<>();
        for (DisplayRackItemVo dri : displayRackItemVoList) {
            if (!ObjectUtils.isEmpty(dri.getCommodityId())) {
                CommodityStoreUpDown commodityStoreUpDownCondition = new CommodityStoreUpDown();
                commodityStoreUpDownCondition.setCommodityId(dri.getCommodityId());
                commodityStoreUpDownCondition.setDeviceId(dri.getDeviceId());
                commodityStoreUpDownCondition.setHierarchy(dri.getHierarchy());
                commodityStoreUpDownCondition.setFreightLane(dri.getFreightLane());
                commodityStoreUpDownCondition.setStatus(CommodityStoreUpDownEnum.GROUNDING.getCode());
                CommodityStoreUpDown commodityStoreUpDown = commodityStoreUpDownService.findOneCommodityStoreUpDownByCondition(commodityStoreUpDownCondition);

                //已经是空的货道没必要插入清货记录
                if (dri.getStock() != 0) {
                    CommodityStockRecord commodityStockRecord = CommodityStockRecord.builder()
                            .userId(displayRackItemDto.getUserId())
                            .merchantStoreId(dri.getMerchantStoreId())
                            .deviceId(dri.getDeviceId())
                            .description("补货上架操作:清货")
                            .outDisplayRackId(dri.getDisplayRackId())
                            .firstType(CommodityStockRecordFirstTypeEnum.OUTBOUND.getCode())
                            .secondaryType(CommodityStockRecordSecondTypeEnum.VENDING_MACHINE_MANUAL_INVENTORY.getCode())
                            .status(CommodityStockRecordStatusEnum.COMPLETED.getCode())
                            .operationUserId(displayRackItemDto.getUserId())
                            .build();
                    commodityStockRecordService.insert(commodityStockRecord);

                    CommodityStockRecordItem commodityStockRecordItem = CommodityStockRecordItem.builder()
                            .commodityStockRecordId(commodityStockRecord.getId())
                            .commodityId(dri.getCommodityId())
                            .quantity(0)
                            .hierarchy(dri.getHierarchy())
                            .freightLane(dri.getFreightLane())
                            .costPrice(commodityStoreUpDown.getCostPrice())
                            .retailPrice(commodityStoreUpDown.getRetailPrice())
                            .stockBefore(dri.getStock())
                            .stockAfter(0)
                            .costPriceBefore(commodityStoreUpDown.getCostPrice())
                            .costPriceAfter(commodityStoreUpDown.getCostPrice())
                            .retailPriceBefore(commodityStoreUpDown.getRetailPrice())
                            .retailPriceAfter(commodityStoreUpDown.getRetailPrice())
                            .remark("补货上架操作:清货")
                            .build();
                    commodityStockRecordItemService.insert(commodityStockRecordItem);
                }

                DisplayRackItemDto update = new DisplayRackItemDto();
                update.setUserId(displayRackItemDto.getUserId());
                update.setId(dri.getId());
                update.setVersion(dri.getVersion());
                update.setStock(0);
                displayRackItemDao.updateByIdAndUserId(update);

                RestockNotificationVo restockNotificationVo = RestockNotificationVo.builder()
                        .goodsId(dri.getCommodityId())
                        .commodityStoreUpDownId(dri.getCommodityStoreUpDownId())
                        .stock(0)
                        .numberOfChanges(-dri.getStock())
                        .deviceNo(dri.getDeviceNo())
                        .hierarchy(dri.getHierarchy())
                        .freightLane(dri.getFreightLane())
                        .name(dri.getName())
                        .retailPrice(dri.getRetailPrice())
                        .costPrice(dri.getCostPrice())
                        .fileName(imageProperties.getBaseUrl() + dri.getFileName())
                        .alias(dri.getAlias())
                        .capacity(dri.getCapacity())
                        .build();
                restockNotificationVoList.add(restockNotificationVo);
            }
        }
        log.info("安卓售货机更新协议准备发送");
        if (displayRackItemVoList.size() > 0
                && !ObjectUtils.isEmpty(displayRackItemVoList.get(0).getIsVendmach())
                && displayRackItemVoList.get(0).getIsVendmach()) {
            String command = PositiveDataFrameCMD.penetrate(HuiLianDuiBiJiPositiveDataFrameCMD.boundDeviceOrUnBindOrEditDiscountPackage());
            log.info("售货机发送更新商品信息:" + command);
            boolean pub = pubService.pub(command, displayRackItemVoList.get(0).getDeviceNo(), productKey);
        }
    }

    /**
     * 查询所有货道并补满 stock库存数
     */
    @Override
    public void fillItUpWithOneKey(DisplayRackItemDto displayRackItemDto) {
        displayRackItemDto.setNotBound(true);
        List<DisplayRackItemVo> displayRackItemVoList = displayRackItemDao.findAllByDeviceId(displayRackItemDto);
        List<RestockNotificationVo> restockNotificationVoList = new ArrayList<>();
        for (DisplayRackItemVo dri : displayRackItemVoList) {
            //绑定了商品，并且货道库存不是最大容量才插入库存记录、修改货道库存、补货通知操作
            if (!ObjectUtils.isEmpty(dri.getCommodityId()) && !Objects.equals(dri.getStock(), dri.getCapacity())) {
                CommodityStoreUpDown commodityStoreUpDownCondition = new CommodityStoreUpDown();
                commodityStoreUpDownCondition.setCommodityId(dri.getCommodityId());
                commodityStoreUpDownCondition.setDeviceId(dri.getDeviceId());
                commodityStoreUpDownCondition.setHierarchy(dri.getHierarchy());
                commodityStoreUpDownCondition.setFreightLane(dri.getFreightLane());
                commodityStoreUpDownCondition.setStatus(CommodityStoreUpDownEnum.GROUNDING.getCode());
                CommodityStoreUpDown commodityStoreUpDown = commodityStoreUpDownService.findOneCommodityStoreUpDownByCondition(commodityStoreUpDownCondition);
                CommodityStockRecord commodityStockRecord = CommodityStockRecord.builder()
                        .userId(displayRackItemDto.getUserId())
                        .merchantStoreId(dri.getMerchantStoreId())
                        .deviceId(dri.getDeviceId())
                        .description("补货上架操作:补满")
                        .inDisplayRackId(dri.getDisplayRackId())
                        .firstType(CommodityStockRecordFirstTypeEnum.INTO_STOCK_ORDER.getCode())
                        .secondaryType(CommodityStockRecordSecondTypeEnum.VENDING_MACHINE_STORE_RECEIPT.getCode())
                        .status(CommodityStockRecordStatusEnum.COMPLETED.getCode())
                        .operationUserId(displayRackItemDto.getUserId())
                        .build();
                commodityStockRecordService.insert(commodityStockRecord);

                CommodityStockRecordItem commodityStockRecordItem = CommodityStockRecordItem.builder()
                        .commodityStockRecordId(commodityStockRecord.getId())
                        .commodityId(dri.getCommodityId())
                        .quantity(dri.getCapacity())
                        .hierarchy(dri.getHierarchy())
                        .freightLane(dri.getFreightLane())
                        .costPrice(commodityStoreUpDown.getCostPrice())
                        .retailPrice(commodityStoreUpDown.getRetailPrice())
                        .stockBefore(dri.getStock())
                        .stockAfter(dri.getCapacity())
                        .costPriceBefore(commodityStoreUpDown.getCostPrice())
                        .costPriceAfter(commodityStoreUpDown.getCostPrice())
                        .retailPriceBefore(commodityStoreUpDown.getRetailPrice())
                        .retailPriceAfter(commodityStoreUpDown.getRetailPrice())
                        .remark("补货上架操作:补满")
                        .build();
                commodityStockRecordItemService.insert(commodityStockRecordItem);

                DisplayRackItemDto update = new DisplayRackItemDto();
                update.setUserId(displayRackItemDto.getUserId());
                update.setId(dri.getId());
                update.setVersion(dri.getVersion());
                update.setStock(dri.getCapacity());
                displayRackItemDao.updateByIdAndUserId(update);

            }
        }
        log.info("安卓售货机更新协议准备发送");
        if (displayRackItemVoList.size() > 0
                && !ObjectUtils.isEmpty(displayRackItemVoList.get(0).getIsVendmach())
                && displayRackItemVoList.get(0).getIsVendmach()) {
            String command = PositiveDataFrameCMD.penetrate(HuiLianDuiBiJiPositiveDataFrameCMD.boundDeviceOrUnBindOrEditDiscountPackage());
            log.info("售货机发送更新商品信息:" + command);
            boolean pub = pubService.pub(command, displayRackItemVoList.get(0).getDeviceNo(), productKey);
        }
    }

    /**
     * 根据freightLane货道 分页查询
     */
    @Override
    public PageInfo findCommodityByHierarchy(DisplayRackItemDto displayRackItemDto) {
        PageHelper.startPage(displayRackItemDto.getPageNum(), displayRackItemDto.getPageSize());
        List<DisplayRackItemVo> displayRackItemVoList = displayRackItemDao.findCommodityByHierarchy(displayRackItemDto);
        return new PageInfo(displayRackItemVoList);
    }

    /**
     * 多选货道 补货
     */
    @Override
    public void multiAisleFilling(DisplayRackItemDto displayRackItemDto) {
        log.info("修改库存设备ID:{}", displayRackItemDto.getDeviceId());
        log.info("前端传入的参数:{}", displayRackItemDto.toString());
        //全选则根据displayRackId查询所有货道信息并补满
        if (displayRackItemDto.getAllSelected()) {
            displayRackItemDto.setIdList(new ArrayList<>());
        } else {
            displayRackItemDto.setDisplayRackId(null);
            if (ObjectUtils.isEmpty(displayRackItemDto.getIdList()) || displayRackItemDto.getIdList().size() <= 0) {
                throw new RuntimeException("未获取到选择的货道信息,请取消重新选择!");
            }
        }
        Product product = productService.findByDeviceId(displayRackItemDto.getDeviceId());
        if (!StringUtils.isEmpty(product) && displayRackItemDto.getCapacity() > product.getCapacity()) {
            throw new RuntimeException("最大容量不能超过售货机实际容量!");
        }
        List<DisplayRackItemVo> displayRackItemVoList = displayRackItemDao.findAllByDeviceId(displayRackItemDto);
        List<RestockNotificationVo> restockNotificationVoList = new ArrayList<>();
        for (DisplayRackItemVo dri : displayRackItemVoList) {

            //插入库存，容量变更记录
            this.inventoryRecords(dri, displayRackItemDto, dri.getMerchantStoreId(), dri.getDeviceId());

            DisplayRackItemDto update = new DisplayRackItemDto();
            update.setUserId(displayRackItemDto.getUserId());
            update.setId(dri.getId());
            update.setVersion(dri.getVersion());
            update.setStock(displayRackItemDto.getStock());
            update.setCapacity(displayRackItemDto.getCapacity());
            displayRackItemDao.updateByIdAndUserId(update);
        }
        log.info("安卓售货机更新协议准备发送");
        if (displayRackItemVoList.size() > 0
                && !ObjectUtils.isEmpty(displayRackItemVoList.get(0).getIsVendmach())
                && displayRackItemVoList.get(0).getIsVendmach()) {
            String command = PositiveDataFrameCMD.penetrate(HuiLianDuiBiJiPositiveDataFrameCMD.boundDeviceOrUnBindOrEditDiscountPackage());
            log.info("售货机发送更新商品信息:" + command);
            boolean pub = pubService.pub(command, displayRackItemVoList.get(0).getDeviceNo(), productKey);
        }
    }

    /**
     * 清空库存 并下架商品
     */
    @Override
    public Integer offTheShelves(DisplayRackItemDto displayRackItemDto) {
        DeviceDto deviceDto = new DeviceDto();
        deviceDto.setUserInfo(displayRackItemDto.getUserInfo());
        deviceDto.setId(displayRackItemDto.getDeviceId());
        DeviceVo deviceVo = deviceService.findDeviceVoById(deviceDto);
        if (deviceVo == null) {
            throw new RuntimeException("设备不存在或暂无权限");
        }

        DisplayRackItemDto findDisplayRackItem = new DisplayRackItemDto();
        findDisplayRackItem.setId(displayRackItemDto.getId());
        DisplayRackItemVo displayRackItem = displayRackItemDao.findDisplayRackItem(findDisplayRackItem);

        CommodityStockRecord storageCommodityStockRecord = CommodityStockRecord.builder()
                .userId(displayRackItemDto.getUserId())
                .merchantStoreId(deviceVo.getMerchantStoreId())
                .deviceId(deviceVo.getId())
                .description("补货上架操作:下架商品")
                .outDisplayRackId(displayRackItem.getDisplayRackId())
                .firstType(CommodityStockRecordFirstTypeEnum.OUTBOUND.getCode())
                .secondaryType(CommodityStockRecordSecondTypeEnum.VENDING_MACHINE_MANUAL_INVENTORY.getCode())
                .status(CommodityStockRecordStatusEnum.COMPLETED.getCode())
                .operationUserId(displayRackItemDto.getUserId())
                .build();
        commodityStockRecordService.insert(storageCommodityStockRecord);
        CommodityStockRecordItem storageCommodityStockRecordItem = CommodityStockRecordItem.builder()
                .commodityStockRecordId(storageCommodityStockRecord.getId())
                .commodityId(displayRackItem.getCommodityId())
                .quantity(0)
                .hierarchy(displayRackItemDto.getHierarchy())
                .freightLane(displayRackItemDto.getFreightLane())
                .costPrice(displayRackItem.getCommodityStoreUpDownCostPrice())
                .retailPrice(displayRackItem.getCommodityStoreUpDownRetailPrice())
                .stockBefore(displayRackItem.getStock())
                .stockAfter(0)
                .costPriceBefore(displayRackItem.getCommodityStoreUpDownCostPrice())
                .costPriceAfter(displayRackItem.getCommodityStoreUpDownCostPrice())
                .retailPriceBefore(displayRackItem.getCommodityStoreUpDownRetailPrice())
                .retailPriceAfter(displayRackItem.getCommodityStoreUpDownRetailPrice())
                .remark("补货上架操作:下架商品")
                .build();
        commodityStockRecordItemService.insert(storageCommodityStockRecordItem);

        /**
         * 下架
         */
        CommodityStoreUpDownDto commodityStoreUpDownDto = new CommodityStoreUpDownDto();
        commodityStoreUpDownDto.setDeviceId(displayRackItemDto.getDeviceId());
        commodityStoreUpDownDto.setHierarchy(displayRackItemDto.getHierarchy());
        commodityStoreUpDownDto.setFreightLane(displayRackItemDto.getFreightLane());
        commodityStoreUpDownDto.setStatus(CommodityStoreUpDownEnum.OFF_SHELF.getCode());
        commodityStoreUpDownService.updateOffTheShelvesById(commodityStoreUpDownDto);

        displayRackItemDto.setCommodityId(null);
        displayRackItemDto.setStock(0);
        log.info("安卓售货机更新协议准备发送");
        if (!ObjectUtils.isEmpty(deviceVo.getIsVendmach())
                && deviceVo.getIsVendmach()) {
            String command = PositiveDataFrameCMD.penetrate(HuiLianDuiBiJiPositiveDataFrameCMD.boundDeviceOrUnBindOrEditDiscountPackage());
            log.info("售货机发送更新商品信息:" + command);
            boolean pub = pubService.pub(command, deviceVo.getDeviceNo(), productKey);
        }
        List<RestockNotificationVo> restockNotificationVoList = new ArrayList<>();
        return displayRackItemDao.updateOffTheShelvesById(displayRackItemDto);
    }

    /**
     * 根据设备id查询该商品缺货数
     */
    @Override
    public DisplayRackItemVo findOutOfStockByDeviceId(DisplayRackItemDto displayRackItemDto) {
        return displayRackItemDao.findOutOfStockByDeviceId(displayRackItemDto);
    }

    /**
     * 缺货盘点
     */
    @Override
    public PageInfo findTakeStockOfOutOfStock(DisplayRackItemDto displayRackItemDto) {
        PageHelper.startPage(displayRackItemDto.getPageNum(), displayRackItemDto.getPageSize());
        List<DisplayRackItemVo> displayRackItemVoList = displayRackItemDao.findTakeStockOfOutOfStock(displayRackItemDto);
        return new PageInfo(displayRackItemVoList);
    }

    /**
     * 缺货详情
     */
    @Override
    public PageInfo findOutOfStockDetails(DisplayRackItemDto displayRackItemDto) {
        displayRackItemDto.setIsDelete(false);
        displayRackItemDto.setNotBound(true);
        displayRackItemDto.setIsOutOfStock(true);
        PageHelper.startPage(displayRackItemDto.getPageNum(), displayRackItemDto.getPageSize());
        List<DisplayRackItemVo> displayRackItemVoList = displayRackItemDao.findAllByDeviceId(displayRackItemDto);
        return new PageInfo(displayRackItemVoList);
    }

    /**
     * 发送检测货道电机
     */
    @Override
    public List<String> sendInspectionTrackMotor(DisplayRackItemDto displayRackItemDto,Integer userId) {
        String detectionKey = String.format(RedisKey.MOTOR_TEST_REFRESH_TIME, displayRackItemDto.getDeviceId());
        if (Boolean.TRUE.equals(redisCacheTemplate.hasKey(detectionKey))) {
            throw new RuntimeException("正在电机检测中，请稍后再试");
        }
        DeviceVo deviceVo = getDeviceVo(displayRackItemDto);
        displayRackItemDto.setDeviceNo(deviceVo.getDeviceNo());
        displayRackItemDto.setEnabled(true);
        displayRackItemDto.setIsDelete(false);
        List<DisplayRackItemVo> displayRackItemVoList = getDisplayRackItemVos(displayRackItemDto);
        List<DisplayRackItemVo> testingList = new ArrayList<>(displayRackItemVoList);
        redisCacheTemplate.opsForValue().set(detectionKey, testingList.size(), testingList.size() * 5L, TimeUnit.SECONDS);
        /**
         * 组装仓位控制参数shipmentList 参数1:层级hierarchy  参数2:货道freightLane   参数3: 控制次数1+00
         * 示例:01010100
         */
        String random;
        if (!StringUtils.isEmpty(deviceVo.getLoginId()) && deviceVo.getLoginId().equals(VendingMachineTypeEnum.ELECTROMAGNETIC_LOCK.getCode())) {
            // 只要是30019的都进入这个协议里面，因为外面已经有主板了，所以只能适配，后期的格子机都用新的协议
            String key = String.format(RedisKey.VENDING_MACHINE_TEST_WAP, deviceVo.getDeviceNo());
            // 缓存要点击测试的的参数
            random = RandomStringUtils.random(6, true, true);
            String command = PositiveDataFrameCMD.penetrate(VendmachPositiveDataFrameCMD.LatticeShipment(random, displayRackItemVoList.get(0).getHierarchy(), displayRackItemVoList.get(0).getFreightLane()));
            pubService.pub(command, deviceVo.getDeviceNo(), productKey);
            displayRackItemVoList.remove(0);
            if (displayRackItemVoList.size() > 0) {
                redisCacheTemplate.opsForValue().set(key, (Serializable) displayRackItemVoList, 20, TimeUnit.MINUTES);
            }
        } else {
            //开门式
            List<OrderItem> orderItemList = new ArrayList<>();
            //除了开门式
            List<OrderItem> latticeOrderItemList = new ArrayList<>();
            Boolean bool = true;
            // 现在是定每30为一组
            Integer time = 30 * 3200;
            for (DisplayRackItemVo d : displayRackItemVoList) {
                if (!StringUtils.isEmpty(d.getDeviceTypeId()) && d.getDeviceTypeId().equals(DeviceTypeEnum.OPEN_DOOR_VENDING_MACHINE.getCode())) {
                    OrderItem latticeOrderItem = new OrderItem();
                    latticeOrderItem.setFreightLane(d.getFreightLane());
                    latticeOrderItem.setHierarchy(d.getHierarchy());
                    latticeOrderItem.setNum(1);
                    latticeOrderItemList.add(latticeOrderItem);
                } else {
                    OrderItem orderItem = new OrderItem();
                    orderItem.setFreightLane(d.getFreightLane());
                    orderItem.setHierarchy(d.getHierarchy());
                    orderItem.setNum(1);
                    orderItemList.add(orderItem);
                }

                if (orderItemList.size() == 30) {
                    time = handleShipment(bool, orderItemList, displayRackItemDto, deviceVo.getIsBluetooth(), time, DeviceTypeEnum.VENDING_MACHINE.getCode(),userId);
                    orderItemList = new ArrayList<>();
                    bool = false;
                }
                if (latticeOrderItemList.size() == 30) {
                    time = handleShipment(bool, latticeOrderItemList, displayRackItemDto, deviceVo.getIsBluetooth(), time, DeviceTypeEnum.OPEN_DOOR_VENDING_MACHINE.getCode(),userId);
                    latticeOrderItemList = new ArrayList<>();
                    bool = false;
                }
            }

            // 处理不足30条的剩余数据
            if (orderItemList.size() > 0) {
                time = handleShipment(bool, orderItemList, displayRackItemDto, deviceVo.getIsBluetooth(), time, DeviceTypeEnum.VENDING_MACHINE.getCode(),userId);
                bool = false;
            }
            if (latticeOrderItemList.size() > 0) {
                time = handleShipment(bool, latticeOrderItemList, displayRackItemDto, deviceVo.getIsBluetooth(), time, DeviceTypeEnum.OPEN_DOOR_VENDING_MACHINE.getCode(),userId);
            }
        }
        for (DisplayRackItemVo d : testingList) {
            final String offlineKey = String.format(RedisKey.MQTT_MOTOR_TESTING_SOCKET_ID, deviceVo.getDeviceNo(), d.getHierarchy(), d.getFreightLane());
            redisCacheTemplate.opsForValue().set(offlineKey, "merchant_" + displayRackItemDto.getUserId(), 10, TimeUnit.MINUTES);
        }
        // 拼接 hierarchy 和 freightLane 字段,返回给前端用于做检测中处理
        return testingList.stream()
                .map(item -> item.getHierarchy() + "" + item.getFreightLane())
                .collect(Collectors.toList());
    }

    public Integer handleShipment(Boolean bool, List<OrderItem> orderItemList, DisplayRackItemDto displayRackItemDto, Boolean isBluetooth, Integer time, Integer deviceTypeId,Integer userId) {
        Map<String, String> delayMap = new HashMap<>();
        if (!StringUtils.isEmpty(isBluetooth) && isBluetooth) {
            String random = org.apache.commons.lang3.RandomStringUtils.random(6, true, true);
            String command = VendmachPositiveDataFrameCMD.LatticeShipmentTestNew(displayRackItemDto.getDeviceNo(), random, orderItemList, LatticeShipmentTestNewCmdEnum.DETECTION.getCode());
            blueToothPubService.pub(command, displayRackItemDto.getDeviceNo(), "merchant_" + userId);
        } else {
            if (bool) {
                String random = org.apache.commons.lang3.RandomStringUtils.random(6, true, true);
                String data = null;
                if (deviceTypeId.equals(DeviceTypeEnum.OPEN_DOOR_VENDING_MACHINE.getCode())) {
                    data = VendmachPositiveDataFrameCMD.LatticeShipmentTestNew(displayRackItemDto.getDeviceNo(), random, orderItemList, LatticeShipmentTestNewCmdEnum.DETECTION.getCode());
                } else {
                    data = VendmachPositiveDataFrameCMD.motorTesting(displayRackItemDto.getDeviceNo(), random, orderItemList);
                }
                String command = PositiveDataFrameCMD.penetrate(data);
                pubService.pub(command, displayRackItemDto.getDeviceNo(), productKey);
            } else {
                delayMap.put("deviceTypeId", deviceTypeId.toString());
                delayMap.put("deviceNo", displayRackItemDto.getDeviceNo());
                delayMap.put("orderItemList", JSON.toJSONString(orderItemList));
                rabbitProducer.sendMotorDetectionEndLazyQueue(delayMap, time);
                time += orderItemList.size() * 4000;
            }
        }
        return time;
    }

    private List<DisplayRackItemVo> getDisplayRackItemVos(DisplayRackItemDto displayRackItemDto) {
        List<DisplayRackItemVo> displayRackItemVoList = displayRackItemDao.findAllByDeviceId(displayRackItemDto);
        if (ObjectUtils.isEmpty(displayRackItemVoList) || displayRackItemVoList.size() == 0) {
            throw new RuntimeException("货道不存在");
        }
        return displayRackItemVoList;
    }

    private DeviceVo getDeviceVo(DisplayRackItemDto displayRackItemDto) {
        DeviceDto deviceDto = new DeviceDto();
        deviceDto.setId(displayRackItemDto.getDeviceId());
        deviceDto.setUserInfo(displayRackItemDto.getUserInfo());
        DeviceVo deviceVo = deviceService.findDeviceVoById(deviceDto);
        if (deviceVo == null) {
            throw new RuntimeException("设备不存在或暂无权限");
        }
        return deviceVo;
    }


    //绑定商品
    @Override
    public Integer updateByIdAndUserId(DisplayRackItemDto displayRackItemDto) throws Exception {
        if (ObjectUtils.isEmpty(displayRackItemDto.getCommodityId())) {
            throw new Exception("缺少参数:商品ID");
        }
        DeviceVo deviceVo = getDeviceVo(displayRackItemDto);

        CommodityVo commodity = commodityService.queryById(displayRackItemDto.getCommodityId());
        CommodityStoreUpDownDto add = new CommodityStoreUpDownDto();
        add.setCommodityId(displayRackItemDto.getCommodityId());
        add.setUserId(displayRackItemDto.getUserId());
        add.setRetailPrice(commodity.getRetailPrice());
        add.setCostPrice(commodity.getCostPrice());
        add.setDeviceId(displayRackItemDto.getDeviceId());
        add.setHierarchy(displayRackItemDto.getHierarchy());
        add.setFreightLane(displayRackItemDto.getFreightLane());
        add.setMerchantStoreId(deviceVo.getMerchantStoreId());
        add.setStatus(CommodityStoreUpDownEnum.GROUNDING.getCode());
        commodityStoreUpDownService.insert(add);

        return displayRackItemDao.updateByIdAndUserId(displayRackItemDto);
    }

    private void inventoryRecords(DisplayRackItemVo displayRackItem, DisplayRackItemDto displayRackItemDto, Integer merchantStoreId, Integer deviceId) {
        if ((!StringUtils.isEmpty(displayRackItemDto.getStock()) && !Objects.equals(displayRackItem.getStock(), displayRackItemDto.getStock())) ||
                (!StringUtils.isEmpty(displayRackItemDto.getCapacity()) && !Objects.equals(displayRackItem.getCapacity(), displayRackItemDto.getCapacity()))) {
            CommodityStockRecord commodityStockRecord = new CommodityStockRecord();
            CommodityStockRecordItem commodityStockRecordItem = new CommodityStockRecordItem();

            commodityStockRecord.setUserId(displayRackItemDto.getUserId());
            commodityStockRecord.setMerchantStoreId(merchantStoreId);
            commodityStockRecord.setDeviceId(deviceId);
            commodityStockRecord.setStatus(CommodityStockRecordStatusEnum.COMPLETED.getCode());
            commodityStockRecord.setOperationUserId(displayRackItemDto.getUserId());

            commodityStockRecordItem.setCommodityId(ObjectUtils.isEmpty(displayRackItemDto.getCommodityId()) ? displayRackItem.getCommodityId() : displayRackItemDto.getCommodityId());
            commodityStockRecordItem.setQuantity(displayRackItemDto.getStock());
            commodityStockRecordItem.setHierarchy(displayRackItem.getHierarchy());
            commodityStockRecordItem.setFreightLane(displayRackItem.getFreightLane());
            commodityStockRecordItem.setCostPrice(ObjectUtils.isEmpty(displayRackItemDto.getCostPrice()) || BigDecimal.ZERO.equals(displayRackItemDto.getCostPrice()) ? displayRackItem.getCostPrice() : displayRackItemDto.getCostPrice());
            commodityStockRecordItem.setRetailPrice(ObjectUtils.isEmpty(displayRackItemDto.getRetailPrice()) || BigDecimal.ZERO.equals(displayRackItemDto.getRetailPrice()) ? displayRackItem.getRetailPrice() : displayRackItemDto.getRetailPrice());

            commodityStockRecordItem.setCostPriceBefore(displayRackItem.getCostPrice());
            commodityStockRecordItem.setCostPriceAfter(ObjectUtils.isEmpty(displayRackItemDto.getCostPrice()) || BigDecimal.ZERO.equals(displayRackItemDto.getCostPrice()) ? displayRackItem.getCostPrice() : displayRackItemDto.getCostPrice());
            commodityStockRecordItem.setRetailPriceBefore(displayRackItem.getRetailPrice());
            commodityStockRecordItem.setRetailPriceAfter(ObjectUtils.isEmpty(displayRackItemDto.getRetailPrice()) || BigDecimal.ZERO.equals(displayRackItemDto.getRetailPrice()) ? displayRackItem.getRetailPrice() : displayRackItemDto.getRetailPrice());

            //插入库存变更记录
            if (!Objects.equals(displayRackItem.getStock(), displayRackItemDto.getStock())) {
                if (displayRackItem.getStock() < displayRackItemDto.getStock()) {
                    commodityStockRecord.setInDisplayRackId(displayRackItem.getDisplayRackId());
                    commodityStockRecord.setFirstType(CommodityStockRecordFirstTypeEnum.INTO_STOCK_ORDER.getCode());
                    commodityStockRecord.setSecondaryType(CommodityStockRecordSecondTypeEnum.VENDING_MACHINE_STORE_RECEIPT.getCode());
                } else {
                    commodityStockRecord.setOutDisplayRackId(displayRackItem.getDisplayRackId());
                    commodityStockRecord.setFirstType(CommodityStockRecordFirstTypeEnum.OUTBOUND.getCode());
                    commodityStockRecord.setSecondaryType(CommodityStockRecordSecondTypeEnum.VENDING_MACHINE_MANUAL_INVENTORY.getCode());
                }
                commodityStockRecord.setDescription("补货上架操作:修改库存");
                commodityStockRecordItem.setRemark("补货上架操作:修改库存");
                commodityStockRecordItem.setStockBefore(displayRackItem.getStock());
                commodityStockRecordItem.setStockAfter(displayRackItemDto.getStock());
                commodityStockRecordService.insert(commodityStockRecord);
                commodityStockRecordItem.setCommodityStockRecordId(commodityStockRecord.getId());
                commodityStockRecordItemService.insert(commodityStockRecordItem);
            }
            //插入容量变更记录
            if (!Objects.equals(displayRackItem.getCapacity(), displayRackItemDto.getCapacity())) {
                commodityStockRecord.setInDisplayRackId(null);
                commodityStockRecord.setOutDisplayRackId(null);
                commodityStockRecord.setFirstType(CommodityStockRecordFirstTypeEnum.INVENTORY_SHEET.getCode());
                commodityStockRecord.setSecondaryType(CommodityStockRecordSecondTypeEnum.TRACK_CAPACITY_MODIFICATION_FORM.getCode());
                commodityStockRecord.setDescription("补货上架操作:修改容量");
                commodityStockRecordItem.setRemark("补货上架操作:修改容量");
                commodityStockRecordItem.setStockBefore(displayRackItem.getCapacity());
                commodityStockRecordItem.setStockAfter(displayRackItemDto.getCapacity());
                commodityStockRecordService.insert(commodityStockRecord);
                commodityStockRecordItem.setCommodityStockRecordId(commodityStockRecord.getId());
                commodityStockRecordItemService.insert(commodityStockRecordItem);
            }
        }
    }

    @Override
    @Transactional
    public Integer updatePrice(DisplayRackItemDto displayRackItemDto) {
        if (ObjectUtils.isEmpty(displayRackItemDto.getCommodityId())) {
            throw new RuntimeException("缺少商品id");
        }
        DeviceVo deviceVo = getDeviceVo(displayRackItemDto);

        Product product = productService.findByDeviceId(displayRackItemDto.getDeviceId());
        if (!StringUtils.isEmpty(product) && displayRackItemDto.getCapacity() > product.getCapacity()) {
            throw new RuntimeException("最大容量不能超过售货机实际容量");
        }
        if (displayRackItemDto.getStock() > displayRackItemDto.getCapacity()) {
            throw new RuntimeException("库存数量不能大于货道容量");
        }

        DisplayRackItemDto findDisplayRackItem = new DisplayRackItemDto();
        findDisplayRackItem.setId(displayRackItemDto.getId());
        DisplayRackItemVo displayRackItem = displayRackItemDao.findDisplayRackItem(findDisplayRackItem);

        //插入库存，容量变更记录
        this.inventoryRecords(displayRackItem, displayRackItemDto, deviceVo.getMerchantStoreId(), deviceVo.getId());

        //修改库存 容量
        displayRackItemDao.updateByIdAndUserId(displayRackItemDto);
        /**
         * 下架
         */
        CommodityStoreUpDownDto commodityStoreUpDownDto = new CommodityStoreUpDownDto();
        commodityStoreUpDownDto.setDeviceId(displayRackItemDto.getDeviceId());
        commodityStoreUpDownDto.setHierarchy(displayRackItemDto.getHierarchy());
        commodityStoreUpDownDto.setFreightLane(displayRackItemDto.getFreightLane());
        commodityStoreUpDownDto.setStatus(CommodityStoreUpDownEnum.OFF_SHELF.getCode());
        commodityStoreUpDownService.updateOffTheShelvesById(commodityStoreUpDownDto);

        CommodityStoreUpDownDto add = new CommodityStoreUpDownDto();
        add.setCommodityId(displayRackItemDto.getCommodityId());
        add.setUserId(displayRackItemDto.getUserId());
        add.setRetailPrice(displayRackItemDto.getRetailPrice());
        add.setCostPrice(ObjectUtils.isEmpty(displayRackItemDto.getCostPrice()) ? BigDecimal.ZERO : displayRackItemDto.getCostPrice());
        add.setDeviceId(displayRackItemDto.getDeviceId());
        add.setHierarchy(displayRackItemDto.getHierarchy());
        add.setFreightLane(displayRackItemDto.getFreightLane());
        add.setMerchantStoreId(deviceVo.getMerchantStoreId());
        add.setStatus(CommodityStoreUpDownEnum.GROUNDING.getCode());


        int result = commodityStoreUpDownService.insert(add);
        log.info("安卓售货机更新协议准备发送");
        if (!ObjectUtils.isEmpty(deviceVo.getIsVendmach())
                && deviceVo.getIsVendmach()) {
            String command = PositiveDataFrameCMD.penetrate(HuiLianDuiBiJiPositiveDataFrameCMD.boundDeviceOrUnBindOrEditDiscountPackage());
            log.info("售货机发送更新商品信息:" + command);
            boolean pub = pubService.pub(command, deviceVo.getDeviceNo(), productKey);
        }
        return result;
    }

    @Override
    public List<DisplayRackItemVo> findOutOfStockDetailsByDisplayRackId(DisplayRackItemDto displayRackItemDto) {
        displayRackItemDto.setIsDelete(false);
        displayRackItemDto.setNotBound(true);
        displayRackItemDto.setIsOutOfStock(true);
        return displayRackItemDao.findAllByDeviceId(displayRackItemDto);
    }

    @Transactional
    @Override
    public ServerResponse batchModifyCommodity(DisplayRackItemDto displayRackItemDto) {
        //全选则根据displayRackId查询所有货道信息并补满
        if (displayRackItemDto.getAllSelected()) {
            displayRackItemDto.setIdList(new ArrayList<>());
        } else {
            displayRackItemDto.setDisplayRackId(null);
        }
        DeviceVo deviceVo = getDeviceVo(displayRackItemDto);
        if (displayRackItemDto.getBatchModifyType() == 1) {
            if (ObjectUtils.isEmpty(displayRackItemDto.getCommodityId())) {
                throw new RuntimeException("缺少商品id");
            }
            Product product = productService.findByDeviceId(displayRackItemDto.getDeviceId());
            if (!StringUtils.isEmpty(product) && displayRackItemDto.getCapacity() > product.getCapacity()) {
                throw new RuntimeException("最大容量不能超过售货机实际容量!");
            }
        }
        displayRackItemDto.setEnabled(true); // 只查询启用的
        List<DisplayRackItemVo> displayRackItemVoList = displayRackItemDao.findDisplayRackitemList(displayRackItemDto);
        for (DisplayRackItemVo displayRackItemVo : displayRackItemVoList) {
            if (displayRackItemDto.getBatchModifyType() != 2) {
                DisplayRackItemDto update = new DisplayRackItemDto();
                update.setUserId(displayRackItemDto.getUserId());
                update.setId(displayRackItemVo.getId());
                update.setVersion(displayRackItemVo.getVersion());
                update.setStock(displayRackItemDto.getStock());
                update.setCapacity(displayRackItemDto.getCapacity());
                update.setCommodityId(displayRackItemDto.getCommodityId());
                displayRackItemDao.updateByIdAndUserId(update);
            }
            if (displayRackItemDto.getBatchModifyType() == 1 || displayRackItemDto.getBatchModifyType() == 2) {
                CommodityStoreUpDownDto commodityStoreUpDownDto = new CommodityStoreUpDownDto();
                commodityStoreUpDownDto.setDeviceId(deviceVo.getId());
                commodityStoreUpDownDto.setHierarchy(displayRackItemVo.getHierarchy());
                commodityStoreUpDownDto.setFreightLane(displayRackItemVo.getFreightLane());
                commodityStoreUpDownDto.setStatus(CommodityStoreUpDownEnum.OFF_SHELF.getCode());
                commodityStoreUpDownService.updateOffTheShelvesById(commodityStoreUpDownDto);

                CommodityStoreUpDownDto add = new CommodityStoreUpDownDto();
                //1为批量修改商品是重新绑定新的商品所以是前端传过来要绑定的商品Id
                if (displayRackItemDto.getBatchModifyType() == 1) {
                    add.setCommodityId(displayRackItemDto.getCommodityId());
                } else {
                    add.setCommodityId(displayRackItemVo.getCommodityId());
                }
                add.setUserId(displayRackItemDto.getUserId());
                add.setRetailPrice(displayRackItemDto.getRetailPrice());
                add.setCostPrice(ObjectUtils.isEmpty(displayRackItemDto.getCostPrice()) ? BigDecimal.ZERO : displayRackItemDto.getCostPrice());
                add.setDeviceId(deviceVo.getId());
                add.setHierarchy(displayRackItemVo.getHierarchy());
                add.setFreightLane(displayRackItemVo.getFreightLane());
                add.setMerchantStoreId(deviceVo.getMerchantStoreId());
                add.setStatus(CommodityStoreUpDownEnum.GROUNDING.getCode());
                commodityStoreUpDownService.insert(add);
            }
            this.inventoryRecords(displayRackItemVo, displayRackItemDto, deviceVo.getMerchantStoreId(), deviceVo.getId());
        }

        log.info("安卓售货机更新协议准备发送");
        if (!ObjectUtils.isEmpty(deviceVo.getIsVendmach())
                && deviceVo.getIsVendmach()) {
            String command = PositiveDataFrameCMD.penetrate(HuiLianDuiBiJiPositiveDataFrameCMD.boundDeviceOrUnBindOrEditDiscountPackage());
            log.info("售货机发送更新商品信息:" + command);
            boolean pub = pubService.pub(command, deviceVo.getDeviceNo(), productKey);
        }
        return ServerResponse.createBySuccess();
    }

    @Override
    public DisplayRackItemVo findOutOfStockByUserId(DisplayRackItemDto displayRackItemDto) {
        return displayRackItemDao.findOutOfStockByUserId(displayRackItemDto);
    }

    @Override
    public List<DisplayRackItemVo> findAllChannelInformationByDeviceId(DisplayRackItemDto displayRackItemDto) {
        return displayRackItemDao.findCommodityByHierarchy(displayRackItemDto);
    }

    @Override
    public DisplayRackVo findDisplayRackAndItemList(DisplayRackItemDto displayRackItemDto) {
        return displayRackItemDao.findDisplayRackAndItemList(displayRackItemDto);
    }

    @Override
    public void updateRestoreByDisplayRackId(Long id) {
        displayRackItemDao.updateRestoreByDisplayRackId(id);
    }

    @Override
    public Integer updateOffEnabledById(DisplayRackItemDto displayRackItemDto) {
        DisplayRackItemVo displayRackItemVo = this.findById(displayRackItemDto);
        displayRackItemDto.setId(displayRackItemVo.getId());
        displayRackItemDto.setVersion(displayRackItemVo.getVersion());
        log.info("安卓售货机更新协议准备发送");
        if (!ObjectUtils.isEmpty(displayRackItemVo.getIsVendmach())
                && displayRackItemVo.getIsVendmach()) {
            String command = PositiveDataFrameCMD.penetrate(HuiLianDuiBiJiPositiveDataFrameCMD.boundDeviceOrUnBindOrEditDiscountPackage());
            log.info("售货机发送更新商品信息:" + command);
            boolean pub = pubService.pub(command, displayRackItemVo.getDeviceNo(), productKey);
        }
        return displayRackItemDao.updateOffEnabledById(displayRackItemDto);
    }

    @Override
    public Integer updateAllOffEnabledById(DisplayRackItemDto displayRackItemDto) {
        if (displayRackItemDto.getIsAll() != null) {
            DisplayRackItemDto update = new DisplayRackItemDto();
            update.setEnabled(displayRackItemDto.getIsAll());
            update.setDeviceId(displayRackItemDto.getDeviceId());
            displayRackItemDao.updateOffEnabledById(update);
        }
        for (DisplayRackItemDto dto : displayRackItemDto.getDisplayRackItemDtos()) {
            dto.setId(dto.getDId());
            DisplayRackItemVo displayRackItemVo = this.findById(dto);
            dto.setUserId(displayRackItemDto.getUserId());
            dto.setVersion(displayRackItemVo.getVersion());
            displayRackItemDao.updateOffEnabledById(dto);
        }
        log.info("安卓售货机更新协议准备发送");
        DeviceVo deviceVo = deviceService.getDeviceById(displayRackItemDto.getDeviceId());
        if (!ObjectUtils.isEmpty(deviceVo.getIsVendmach())
                && deviceVo.getIsVendmach()) {
            String command = PositiveDataFrameCMD.penetrate(HuiLianDuiBiJiPositiveDataFrameCMD.boundDeviceOrUnBindOrEditDiscountPackage());
            log.info("售货机发送更新商品信息:" + command);
            boolean pub = pubService.pub(command, deviceVo.getDeviceNo(), productKey);
        }
        return 0;
    }

    @Override
    public Integer updateAliasById(DisplayRackItemDto displayRackItemDto) {
        DisplayRackItemVo displayRackItemVo = this.findById(displayRackItemDto);
        displayRackItemDto.setId(displayRackItemVo.getId());
        displayRackItemDto.setVersion(displayRackItemVo.getVersion());
        return displayRackItemDao.updateAliasById(displayRackItemDto);
    }


    @Override
    public DisplayRackItemVo findById(DisplayRackItemDto displayRackItemDto) {
        return displayRackItemDao.findById(displayRackItemDto);
    }


}
